const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

exports.main = async (event, context) => {
  const { avatarUrl, nickname } = event;
  const wxContext = cloud.getWXContext(); // 获取 openid
  const openid = wxContext.OPENID;

  const db = cloud.database();

  try {
    // 查询是否已经存在该 openid 的记录
    const checkUser = await db.collection('userProfile').where({
      openid: openid
    }).get();

    if (checkUser.data.length > 0) {
      // 如果用户已存在，不做任何操作
      return {
        success: true,
        message: '用户已存在',
        openid: openid,
      };
    } else {
      // 如果用户不存在，新增用户记录
      await db.collection('userProfile').add({
        data: {
          avatarUrl: avatarUrl,
          nickname: nickname,
          openid: openid,
          createTime: new Date()
        }
      });

      return {
        success: true,
        message: '用户已创建',
        openid: openid,
        _id: res._id,
      };
    }
  } catch (error) {
    console.error('Error saving user profile:', error);
    return {
      success: false,
      error
    };
  }
};
